﻿using System;
using System.Collections.Generic;
using System.Reflection;
using MySql.Data.MySqlClient;
using System.Data;

namespace DBTools
{
    internal static class DB
    {
        private static MySqlConnection conn;

        public static string DataBase { get => conn.Database; }

        public static void Init(string host, string user, string passwd, string port = "3306", string database = "INFORMATION_SCHEMA")
        {
            var str = new MySqlConnectionStringBuilder()
            {
                Server = host,
                UserID = user,
                Port = 3306,
                Password = passwd,
                AllowUserVariables = true,
                CharacterSet = "utf8",
                Database = database,
                Pooling = true,
            }.ConnectionString;
        }
        //=> (conn = new MySqlConnection($"host={host};user={user};port={port};password={passwd};Allow User Variables=True;Charset=utf8;database={database};")).Open();

        public static void Init(string connectionString)
            => (conn = new MySqlConnection(connectionString)).Open();

        public static void SetDataBase(string database) => conn.ChangeDatabase(database);

        public static DataTable ExecuteToDataTable(string strSql)
        {
            using (MySqlDataAdapter adapt = new MySqlDataAdapter(strSql, conn))
            {
                DataTable dt = new DataTable();
                adapt.Fill(dt);
                return dt;
            }
        }

        public static object ExecuteScalar(string strSql)
        {
            using (MySqlCommand cmd = new MySqlCommand(strSql, conn))
            {
                return cmd.ExecuteScalar();
            }
        }

        public static List<string> ExecuteToList(string strSql)
        {
            using (MySqlDataReader reader = new MySqlCommand(strSql, conn).ExecuteReader())
            {
                List<string> res = new List<string>();
                while (reader.Read())
                {
                    res.Add(reader.GetString(0));
                }

                return res;
            }
        }
    }
}
